﻿#include "usermanagetableview.h"
#include "dbhelper.h"

UserManageTableView::UserManageTableView(QWidget *parent) : MyTableView(parent)
{
    model = new UserManageStandardItemModel();
    setModel(model);

    totalTicketIn = 0;
    totalTicketOut = 0;
    totalMoneyIn = 0;
    totalMoneyOut = 0;
    setEditTriggers(QAbstractItemView::NoEditTriggers);
}

void UserManageTableView::setWidgetType(UserRelation::RelationType widgetType)
{
    this->widgetType = widgetType;
    model->setHeader(widgetType);
}

void UserManageTableView::initHiddenState(){
    if(widgetType == UserRelation::Client){
        initHiddenStateList("client", model->header.size());
    }else {
        initHiddenStateList("giver", model->header.size());
    }
}

void UserManageTableView::setListPushButton(ListPushButton *listPushButton){
    setListPushButtonAndMenuLabel(listPushButton, model->header);
}

void UserManageTableView::clear()
{
    model->reset();
    model->setHeader(widgetType);
    refreshHiddenState();
}

void UserManageTableView::insertUserRelation(QList<UserRelation*> relations, bool isShowPlatformUser)
{
    totalTicketIn = 0;
    totalTicketOut = 0;
    totalMoneyIn = 0;
    totalMoneyOut = 0;
    for(UserRelation *relation:relations){
        totalTicketIn += relation->ticketIn-relation->preTicketIn;
        totalTicketOut += relation->ticketOut-relation->preTicketOut;
        totalMoneyIn += relation->moneyIn-relation->preMoneyIn;
        totalMoneyOut += relation->moneyOut-relation->preMoneyOut;
    }
    emit refreshUserRelationData(totalTicketIn, totalTicketOut, totalMoneyIn, totalMoneyOut);
    model->insertUserRelation(relations, isShowPlatformUser);
}

void UserManageTableView::loadUserRelations(bool isShowPlatformUser)
{
    DbHelper helper;
    QList<UserRelation*> relations = helper.getAllUserRelationsByType(widgetType);
    insertUserRelation(relations, isShowPlatformUser);
}

void UserManageTableView::queryUserRelation(
        bool isShowPlatformUser,
        QString overallQuery,
        QString nickNameQuery,
        QString contactQuery,
        QString telQuery,
        QString primaryQuery,
        QString secondaryQuery)
{
    clear();
    DbHelper helper;

    QList<UserRelation*> relations = helper.queryUserRelation(
                widgetType,
                overallQuery,
                nickNameQuery,
                contactQuery,
                telQuery,
                primaryQuery,
                secondaryQuery);

    insertUserRelation(relations, isShowPlatformUser);

    emit this->refreshUserRelationData(
                totalTicketIn,
                totalTicketOut,
                totalMoneyIn,
                totalMoneyOut);
}

UserRelation* UserManageTableView::currentUserRelation()
{
    int row = currentIndex().row();

    return model->getUserRelation(row);
}
